from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

mail_host = 'smtp.gmail.com'
sender = 'hand*****@gmail.com'
receivers = ['13****08@qq.com','ca**@gmail.com']
mail_pass = '*****'

# content = MIMEMultipart()  #建立MIMEMultipart物件
# content["subject"] = "Learn Code With WS"  #邮件标题
# content["from"] = sender #"pydemo123@gmail.com"  #寄件者
# content["to"] = receivers[1] #"example@gmail.com" #收件者
# content.attach(MIMEText("Demo python send email"))  #邮件內容


from string import Template
from pathlib import Path
user = 'wushuai'
content = MIMEMultipart()  # 建立MIMEMultipart物件
content["subject"] = "Learn Code With WS"  # 郵件標題
content["from"] = sender #"pydemo123@gmail.com"  #寄件者
content["to"] = receivers[0] #"example@gmail.com"

template = Template(Path("ws_gmail.html").read_text())
body = template.substitute({ "user": "WuShuai" })

content.attach(MIMEText(body, "html"))  # HTML郵件內容



import smtplib
with smtplib.SMTP(host="smtp.gmail.com", port="587") as smtp:  # 設定SMTP伺服器
    try:
        smtp.ehlo()  # 驗證SMTP伺服器
        smtp.starttls()  # 建立加密傳輸
        smtp.login(sender,mail_pass)  # 登入寄件者gmail
        smtp.send_message(content)  # 寄送郵件
        print("Complete!")
    except Exception as e:
        print("Error message: ", e)
